package com.uduemc.biso.node.web.service.html.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.node.core.common.dto.FeignFindSiteInformationList;
import com.uduemc.biso.node.core.common.dto.FeignFindSitePdtableList;
import com.uduemc.biso.node.core.common.dto.information.InformationTitleItem;
import com.uduemc.biso.node.core.common.entities.SitePage;
import com.uduemc.biso.node.core.common.sysconfig.DownloadSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.FaqSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.InformationSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.PdtableSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.ProductSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.informationsysconfig.InformationSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.pdtablesysconfig.PdtableSysListConfig;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SDownloadAttr;
import com.uduemc.biso.node.core.entities.SFaq;
import com.uduemc.biso.node.core.entities.SInformationTitle;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.core.entities.custom.Download;
import com.uduemc.biso.node.core.entities.custom.InformationList;
import com.uduemc.biso.node.core.entities.custom.PdtableList;
import com.uduemc.biso.node.core.entities.custom.ProductDataTableForList;
import com.uduemc.biso.node.core.utils.SystemConfigUtil;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.component.html.HSystemDownloadItemListUdin;
import com.uduemc.biso.node.web.component.html.HSystemFaqItemListUdin;
import com.uduemc.biso.node.web.component.html.HSystemInformationItemListUdin;
import com.uduemc.biso.node.web.component.html.HSystemPdtableItemListUdin;
import com.uduemc.biso.node.web.component.html.HSystemProductItemListUdin;
import com.uduemc.biso.node.web.entities.AccessPage;
import com.uduemc.biso.node.web.exception.NotFound404Exception;
import com.uduemc.biso.node.web.service.ContentService;
import com.uduemc.biso.node.web.service.byfeign.CategoryService;
import com.uduemc.biso.node.web.service.byfeign.DownloadService;
import com.uduemc.biso.node.web.service.byfeign.FaqService;
import com.uduemc.biso.node.web.service.byfeign.InformationService;
import com.uduemc.biso.node.web.service.byfeign.PdtableService;
import com.uduemc.biso.node.web.service.byfeign.ProductService;
import com.uduemc.biso.node.web.service.html.BasicUdinService;
import com.uduemc.biso.node.web.service.html.HPLCompService;
import com.uduemc.biso.node.web.utils.AssetsResponseUtil;
import com.uduemc.biso.node.web.utils.StringFilterUtil;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class HPLCompServiceImpl implements BasicUdinService, HPLCompService {

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private ProductService productServiceImpl;

	@Autowired
	private DownloadService downloadServiceImpl;

	@Autowired
	private CategoryService categoryServiceImpl;

	@Autowired
	private FaqService faqServiceImpl;

	@Autowired
	private InformationService informationServiceImpl;

	@Autowired
	private PdtableService pdtableServiceImpl;

	@Autowired
	private HSystemProductItemListUdin hSystemProductItemListUdin;

	@Autowired
	private HSystemDownloadItemListUdin hSystemDownloadItemListUdin;

	@Autowired
	private HSystemFaqItemListUdin hSystemFaqItemListUdin;

	@Autowired
	private HSystemInformationItemListUdin hSystemInformationItemListUdin;

	@Autowired
	private HSystemPdtableItemListUdin hSystemPdtableItemListUdin;

	@Autowired
	private ContentService contentServiceImpl;

	@Override
	public StringBuilder html() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException, NotFound404Exception {
		AccessPage accessPage = requestHolder.getAccessPage();

		// 系统
		SSystem system = accessPage.getSystem();

		// 页面 page 数据
		SitePage sitePage = accessPage.getSitePage();
		SPage page = sitePage.getSPage();

		// 当前的系统分类，可以没有分类
		SCategories category = sitePage.getSCategories();

		// 是否搜索，如果是搜索，那么搜索的关键字是什么
		HttpServletRequest request = requestHolder.getRequest();
		String keyword = StringFilterUtil.keywordFilter(request.getParameter("k"));

		// 当前页数
		int pageNum = sitePage.getPageNum();

		// 通过页面的类型决定执行的方法
		String templateName = requestHolder.getAccessPage().getSitePage().getTemplateName();
		if (templateName.equals("cate")) {
			// 产品系统列表页面
			return catehtml(system, page, category, pageNum, keyword);// new StringBuilder("<!-- PLComp -->");
		} else if (templateName.equals("downlist")) {
			// 下载系统列表页面
			return downlisthtml(system, page, category, pageNum, keyword);// new StringBuilder("<!-- FileLComp -->");
		} else if (templateName.equals("faqlist")) {
			// FAQ系统列表页面
			return faqlisthtml(system, page, category, pageNum, keyword);
		} else if (templateName.equals("informationlist")) {
			// 信息系统列表页面
			return informationlisthtml(system, page, pageNum, keyword);
		} else if (templateName.equals("pdtablelist")) {
			// 产品表格系统列表页面
			return pdtableitem(system, page, category, pageNum, keyword);
		}

		return new StringBuilder("<!-- HPLCompServiceImpl undefined templateName: " + templateName + " -->");
	}

	@Override
	public StringBuilder catehtml(SSystem system, SPage page, SCategories category, int pageNum, String keyword)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (system == null || page == null) {
			return new StringBuilder("<!-- PLComp system or page null -->");
		}

		// 获取系统配置
		ProductSysConfig productSysConfig = SystemConfigUtil.productSysConfig(system);

		// 通过配置获取 每页显示的产品数量
		int pagesize = productSysConfig.getList().getPer_page();

		long hostId = system.getHostId();
		long siteId = system.getSiteId();
		long systemId = system.getId();
		long categoryId = -1;
		if (category != null) {
			categoryId = category.getId().longValue();
		}

		keyword = StrUtil.isBlank(keyword) ? "" : StrUtil.trim(keyword);
		// 获取数据
		PageInfo<ProductDataTableForList> pageInfoProduct = productServiceImpl.getInfosBySystemCategoryIdKeywordAndPage(hostId, siteId, systemId, categoryId,
				keyword, pageNum, pagesize);
		List<ProductDataTableForList> listProductDataTableForList = pageInfoProduct != null ? pageInfoProduct.getList() : null;
		// 数据总数
		int total = pageInfoProduct != null ? (int) pageInfoProduct.getTotal() : 0;

		// 制作面包屑时需要分类列表数据
		// 通过系统数据，获取该系统下的所有分类数据！
		List<SCategories> listSCategories = categoryServiceImpl.getInfosByHostSiteSystemIdAndDefaultOrder(system.getHostId(), system.getSiteId(),
				system.getId());

		return AssetsResponseUtil.htmlCompress(hSystemProductItemListUdin.html(productSysConfig, page, category, listProductDataTableForList, listSCategories,
				keyword, pageNum, total, pagesize), false);
	}

	@Override
	public StringBuilder downlisthtml(SSystem system, SPage page, SCategories category, int pageNum, String keyword)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (system == null || page == null) {
			return new StringBuilder("<!-- DownloadLComp system or page null -->");
		}
		// 获取系统配置
		DownloadSysConfig downloadSysConfig = SystemConfigUtil.downloadSysConfig(system);

		// 通过配置获取 每页显示的产品数量
		int pageSize = downloadSysConfig.getList().getPerpage();
		long hostId = system.getHostId();
		long siteId = system.getSiteId();
		long systemId = system.getId();
		long categoryId = -1;
		if (category != null) {
			categoryId = category.getId().longValue();
		}

		PageInfo<Download> pageInfoDownload = downloadServiceImpl.getInfosBySystemCategoryIdKeywordAndPage(hostId, siteId, systemId, categoryId, keyword,
				pageNum, pageSize);
		List<Download> listDownload = pageInfoDownload != null ? pageInfoDownload.getList() : null;

		// 数据总数
		int total = pageInfoDownload != null ? (int) pageInfoDownload.getTotal() : 0;

		// 制作面包屑时需要分类列表数据
		// 通过系统数据，获取该系统下的所有分类数据！
		List<SCategories> listSCategories = categoryServiceImpl.getInfosByHostSiteSystemIdAndDefaultOrder(system.getHostId(), system.getSiteId(),
				system.getId());

		List<SDownloadAttr> listSDownloadAttr = downloadServiceImpl.getAttrInfosByHostSiteSystemId(hostId, siteId, systemId);

		return AssetsResponseUtil.htmlCompress(hSystemDownloadItemListUdin.html(downloadSysConfig, page, category, listSDownloadAttr, listDownload,
				listSCategories, keyword, pageNum, total, pageSize), false);
	}

	@Override
	public StringBuilder faqlisthtml(SSystem system, SPage page, SCategories category, int pageNum, String keyword) throws IOException {
		if (system == null || page == null) {
			return new StringBuilder("<!-- FAQLComp system or page null -->");
		}
		// 获取系统配置
		FaqSysConfig faqSysConfig = SystemConfigUtil.faqSysConfig(system);

		// 通过配置获取 每页显示的FAQ数量
		int pageSize = faqSysConfig.getList().getPerpage();
		long hostId = system.getHostId();
		long siteId = system.getSiteId();
		long systemId = system.getId();
		long categoryId = -1;
		if (category != null) {
			categoryId = category.getId().longValue();
		}

		PageInfo<SFaq> pageInfoFaq = faqServiceImpl.infosBySystemCategoryIdKeywordAndPage(hostId, siteId, systemId, categoryId, keyword, pageNum, pageSize);
		List<SFaq> listFaq = pageInfoFaq != null ? pageInfoFaq.getList() : null;

		// 过滤富文本中的内容
		if (CollUtil.isNotEmpty(listFaq)) {
			for (SFaq sFaq : listFaq) {
				sFaq.setInfo(contentServiceImpl.filterUEditorContentWithSite(sFaq.getInfo()));
			}
		}

		// 数据总数
		int total = pageInfoFaq != null ? (int) pageInfoFaq.getTotal() : 0;

		// 制作面包屑时需要分类列表数据
		// 通过系统数据，获取该系统下的所有分类数据！
		List<SCategories> listSCategories = categoryServiceImpl.getInfosByHostSiteSystemIdAndDefaultOrder(system.getHostId(), system.getSiteId(),
				system.getId());

		return AssetsResponseUtil
				.htmlCompress(hSystemFaqItemListUdin.html(faqSysConfig, page, category, listFaq, listSCategories, keyword, pageNum, total, pageSize), false);
	}

	@Override
	public StringBuilder informationlisthtml(SSystem system, SPage page, int pageNum, String keyword) throws IOException {
		if (system == null || page == null) {
			return new StringBuilder("<!-- InformationLComp system or page null -->");
		}
		// 获取系统配置
		InformationSysConfig informationSysConfig = SystemConfigUtil.informationSysConfig(system);
		InformationSysListConfig list = informationSysConfig.getList();
		int searchtype = list.getSearchtype();
		int orderby = list.getOrderby();
		int perpage = list.getPerpage();

		long hostId = system.getHostId();
		long siteId = system.getSiteId();
		long systemId = system.getId();

		keyword = StringFilterUtil.keywordDefilter(keyword);

		List<SInformationTitle> listSInformationTitle = informationServiceImpl.findOkSInformationTitleByHostSiteSystemId(hostId, siteId, systemId);
		List<InformationTitleItem> listInformationTitleItem = new ArrayList<>();
		if (StrUtil.isNotBlank(keyword)) {
			String[] split = keyword.split(";");
			if (ArrayUtil.isNotEmpty(split)) {
				for (String str : split) {
					String[] spl = str.split(",");
					if (ArrayUtil.isNotEmpty(spl) && ArrayUtil.length(spl) == 2) {
						String k1 = spl[0];
						String k2 = StringFilterUtil.keywordFilter(spl[1]);
						k2 = StrUtil.trim(k2);
						if (NumberUtil.isNumber(k1) && StrUtil.isNotBlank(k2)) {
							long binaryToLong = Long.valueOf(k1);
							Optional<SInformationTitle> findFirst = listSInformationTitle.stream().filter(item -> {
								return item.getId().longValue() == binaryToLong;
							}).findFirst();
							if (findFirst.isPresent()) {
								listInformationTitleItem.add(new InformationTitleItem(binaryToLong, k2));
							}
						}
					}
				}
			}
		}

		FeignFindSiteInformationList feignFindSiteInformationList = new FeignFindSiteInformationList();
		feignFindSiteInformationList.setHostId(hostId).setSiteId(siteId).setSystemId(systemId);
		feignFindSiteInformationList.setSearchType(searchtype).setOrderBy(orderby).setPage(pageNum).setSize(perpage);
		feignFindSiteInformationList.setKeyword(listInformationTitleItem);

		InformationList informationList = informationServiceImpl.findSiteInformationList(feignFindSiteInformationList);

		return AssetsResponseUtil.htmlCompress(hSystemInformationItemListUdin.html(system, page, informationList, listInformationTitleItem, pageNum), false);
	}

	@Override
	public StringBuilder pdtableitem(SSystem system, SPage page, SCategories category, int pageNum, String keyword) throws IOException {
		if (system == null || page == null) {
			return new StringBuilder("<!-- PdtableLComp system or page null -->");
		}

		// 获取系统配置
		PdtableSysConfig pdtableSysConfig = SystemConfigUtil.pdtableSysConfig(system);
		PdtableSysListConfig list = pdtableSysConfig.getList();
		int orderby = list.getOrderby();
		int perpage = list.getPerpage();
		long hostId = system.getHostId();
		long siteId = system.getSiteId();
		long systemId = system.getId();

		List<Long> categoryIds = new ArrayList<>();
		if (category != null) {
			categoryIds.add(category.getId());
		}

		FeignFindSitePdtableList findSitePdtableList = new FeignFindSitePdtableList();
		findSitePdtableList.setHostId(hostId).setSiteId(siteId).setSystemId(systemId).setCategoryIds(categoryIds).setReleasedAt(DateUtil.date().toJdkDate())
				.setKeyword(keyword).setOrderBy(orderby).setPage(pageNum).setSize(perpage);
		PdtableList pdtableList = pdtableServiceImpl.findSitePdtableList(findSitePdtableList);
		// 制作面包屑时需要分类列表数据
		// 通过系统数据，获取该系统下的所有分类数据！
		List<SCategories> listSCategories = categoryServiceImpl.getInfosByHostSiteSystemIdAndDefaultOrder(system.getHostId(), system.getSiteId(),
				system.getId());

		return AssetsResponseUtil.htmlCompress(hSystemPdtableItemListUdin.html(system, page, pdtableList, category, listSCategories, keyword, pageNum), false);
	}
}
